<?php
// +----------------------------------------------------------------------
// | BhAdmin [ BhAdmin匠心打造，我们相信，每个伟大的软件都有一个伟大的故事 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2023 https://www.bhadmin.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed BhAdmin并不是自由软件，未经许可不能去掉BhAdmin相关版权
// +----------------------------------------------------------------------
// | Author: BAIHU  <admin@bhadmin.cn>
// +----------------------------------------------------------------------
namespace app\admin\logic;

use app\admin\validate\AdValidate;
use support\Backend\BackendLogic;
use support\Container;
use support\Exception\ApiException;
use support\Service\AdService;

class AdLogic extends BackendLogic
{
    public function __construct()
    {
        $this->service = Container::get(AdService::class);
    }

    /**
     * 获取列表
     * @return array
     */
    public function getList(): array
    {
        $param = request()->get();
        $where[] = ["mark", '=', 1];
        if (!empty($param['name'])) {
            $where[] = ["name", '=', $param['name']];
        }
        if (!empty($param['create_time'])) {
            $where[] = ["create_time", '>=', strtotime($param['create_time'][0])];
            $where[] = ["create_time", '<=', strtotime($param['create_time'][1])];
        }
        $list = $this->service->getListPage($where);
        if ($list['total'] <= 0) return message($list);
        return message($list);
    }


    /**
     * 新增或者编辑
     * @return array
     */
    public function edit(): array
    {
        $data = request()->post();
        $validate = new AdValidate();
        if (!$validate->check($data)) throw new ApiException($validate->getError());
        $save['id'] = $data['id'] ?? 0;
        $save['name'] = trim($data['name']);
        $save['url'] = $data['url'];
        if (in_array('1', $data['device'])) {
            $save['device'] = '1';
        } else {
            $save['device'] = implode(',', $data['device']);
        }
        $save['cover'] = $data['cover'];
        $save['sort'] = $data['sort'];
        $save['start_time'] = strtotime($data['time_range'][0]);
        $save['end_time'] = strtotime($data['time_range'][1]);
        $save['status'] = $data['status'] ?? 1;
        $save['content'] = $data['content'] ?? '';
        $this->service->edit($save);
        return message();

    }


}
